<template>
  <div class="step2">
    <h2>
      {{ $t("breach.steps.step2.title") }}
    </h2>
    <div class="base-info">
      <h3 class="mb-[10px]">{{ $t("breach.steps.step2.baseinfo.title") }}</h3>
      <a-form
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 21 }"
        labelAlign="left"
        layout="horizontal"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item :label="$t('breach.steps.step2.baseinfo.informant')">
              <a-input
                :disabled="true"
                v-model="childBreachDetail.EventCreatorStr"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('breach.list.content.table.id')">
              <a-input
                :disabled="true"
                v-model="childBreachDetail.EventId"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <step-1
        ref="step1"
        :breachMode="breachMode"
        :lang="lang"
        :breachDetail="childBreachDetail"
        :ifCanEdit="
          ifCanEdit &&
          (role.includes('processor') || role.includes('shareEdit'))
        "
        :ifDispatch="true"
        :ifStep2="true"
      />
    </div>
    <div
      class="business mb-[10px]"
      v-for="(item, outInd) in businessList"
      :key="item.Id"
    >
      <h3 class="mb-[10px]">{{ $t("breach.steps.step2.business.title") }}</h3>
      <div class="status-steps">
        <div class="step orange">{{ $t("menu.list.search-list112233") }}</div>
        <a-icon
          :class="item.SupplementStatus > 1 ? 'light-green' : ''"
          type="right-circle"
        />
        <div :class="['step', item.SupplementStatus > 1 ? 'green' : '']">
          {{ $t("breach.steps.step2.business.status.assigned") }}
        </div>
        <a-icon
          :class="item.SupplementStatus === 3 ? 'blue' : ''"
          type="right-circle"
        />
        <div :class="['step', item.SupplementStatus === 3 ? 'light-blue' : '']">
          {{ $t("breach.steps.step2.business.status.completed") }}
        </div>
      </div>
      <a-popconfirm
        :title="$t('user.verification-code.required111566110577225')"
        :ok-text="$t('user.verification-code.required1166')"
        :cancel-text="$t('user.email.required11')"
        :disabled="!(role.includes('processor') || role.includes('shareEdit'))"
        @confirm="() => delBussiness(item.Id)"
      >
        <a-button
          class="delete-btn"
          icon="delete"
          type="link"
          :disabled="
            !(role.includes('processor') || role.includes('shareEdit'))
          "
          v-if="businessList.length > 1 && item.SupplementStatus === 1"
        ></a-button>
      </a-popconfirm>
      <div class="patch">
        <label>
          <span>{{ $t("breach.steps.step2.business.patch.user") }}:</span>
          <a-select
            v-model="item.SupplementUser"
            :placeholder="$t('breach.steps.step1.content.form.tip1')"
            :disabled="
              !ifCanEdit ||
              !role.includes('processor') ||
              (role.includes('processor') && item.SupplementStatus === 3)
            "
            show-search
            @search="getUsers"
          >
            <a-select-option v-for="item in handlerList" :key="item.value">{{
              item.label
            }}</a-select-option>
          </a-select>
        </label>
        <a-button
          type="link"
          :disabled="!role.includes('processor') || !item.SupplementUser"
          :loading="btnLoading"
          @click="patchUser(item)"
        >
          <img
            :src="
              require(role.includes('processor') && item.SupplementUser
                ? '@/assets/svg/breach/patch.svg'
                : '@/assets/svg/breach/patchDisabled.svg')
            "
            class="mr-[6px]"
            alt=""
          />
          {{
            $t(
              item?.frontTemp?.ifPatched
                ? "breach.steps.step2.business.patch.resubmit"
                : "breach.steps.step2.business.patch.submit"
            )
          }}
        </a-button>
      </div>
      <div
        class="collaborators"
        v-for="(collaborator, ind) in item.collaborators"
        :key="collaborator + ind"
      >
        <label>
          <span>
            {{
              $t("breach.steps.step2.business.collaboration.user") + (ind + 1)
            }}:
          </span>
          <a-select
            v-model="collaborator.SharingUser"
            :placeholder="$t('breach.steps.step1.content.form.tip1')"
            :disabled="
              !ifCanEdit ||
              (!role.includes('processor') && item.SupplementStatus === 3)
            "
            show-search
            @search="getUsers"
          >
            <a-select-option
              v-for="handler in handlerList"
              :key="handler.value"
              :disabled="
                item.collaborators
                  ?.map((item) => item.SharingUser)
                  .includes(handler.value)
              "
              >{{ $t(handler.label) }}</a-select-option
            >
          </a-select>
        </label>
        <a-icon
          type="minus-circle"
          theme="filled"
          :class="
            !ifCanEdit ||
            (!role.includes('processor') && item.SupplementStatus === 3)
              ? 'disabled'
              : ''
          "
          @click="delCollaborator(item, collaborator, ind)"
        />
      </div>
      <a-button
        icon="plus"
        type="link"
        v-if="item.collaborators && item.collaborators.length < 6"
        :disabled="
          item.SupplementUser !== $store.state.user.info.YtAdminName ||
          !ifCanEdit ||
          (!role.includes('processor') && item.SupplementStatus === 3)
        "
        @click="
          item.collaborators.push({ Id: +new Date(), SharingUser: undefined })
        "
        >{{ $t("breach.steps.step2.business.collaboration.add") }}</a-button
      >
      <step-2-form
        :ref="`step2Form${outInd}`"
        :style="{
          maxHeight: item?.frontTemp?.ifShrink ? 0 : '10000px',
        }"
        :item="item"
        :lang="lang"
        :ifCanEdit="
          ifCanEdit &&
          (role.includes('processor') ||
            role.includes('shareEdit') ||
            ((role.includes('business') || role.includes('Collaborator')) &&
              item.SupplementStatus !== 3))
        "
        :role="role"
        :breachMode="breachMode"
        :breachDetail="childBreachDetail"
        :current="current"
        @changeItem="(...rest) => changeItem(item, ...rest)"
        @saveItem="saveItem"
        @saveDraft="saveDraft"
      />
      <footer>
        <a-button
          type="link"
          @click="item.frontTemp.ifShrink = !item.frontTemp.ifShrink"
        >
          <a-icon type="double-right" v-if="!item?.frontTemp?.ifShrink" />
          {{
            $t(
              `breach.steps.step2.business.footer.shrink.${item.frontTemp.ifShrink}`
            )
          }}
          <a-icon type="double-left" v-if="item?.frontTemp?.ifShrink" />
        </a-button>
      </footer>
    </div>
    <a-button
      icon="plus"
      type="primary"
      @click="addSupplement"
      :disabled="
        !ifCanEdit ||
        !(role.includes('processor') || role.includes('shareEdit'))
      "
      >{{ $t("breach.steps.step2.buttons.addbusiness") }}</a-button
    >
    <div class="step-buttons">
      <!-- 保存 -->
      <a-button
        type="primary"
        class="mr-[20px]"
        :disabled="
          !(role.includes('processor') || role.includes('shareEdit')) ||
          !ifCanEdit
        "
        @click="saveDraft"
        >{{ $t("breach.steps.step2.business.form.buttons.save") }}</a-button
      >
      <!-- 转办 -->
      <a-button
        class="mr-[20px]"
        :disabled="!ifCanEdit || !role.includes('processor')"
        @click="visible = true"
      >
        {{ $t("breach.steps.step2.buttons.turn") }}
      </a-button>
      <!-- 下一步 -->
      <a-button class="mr-[20px]" type="primary" @click="changeStep(2)">
        {{ $t("breach.steps.step2.buttons.next") }}
        <a-icon type="right" />
      </a-button>
      <!-- 预览报告 -->
      <a-button
        type="primary"
        :disabled="
          !(
            role.includes('processor') ||
            role.includes('shareEdit') ||
            role.includes('shareView')
          )
        "
        @click="changeStep(3)"
      >
        {{ $t("breach.steps.step2.buttons.review") }}
      </a-button>
    </div>
    <a-modal
      v-model="visible"
      :closable="false"
      :title="$t('breach.steps.step2.turn.title')"
    >
      <a-form :form="form">
        <a-form-item :label="$t('breach.steps.step2.turn.processor')">
          <a-select
            :placeholder="$t('breach.steps.step2.turn.processor.placeholder')"
            :disabled="!ifCanEdit"
            v-decorator="[
              'BreachCommentsProcessorId',
              {
                rules: [
                  {
                    required: true,
                    message: $t('breach.steps.step2.turn.processor'),
                  },
                ],
              },
            ]"
            show-search
            option-filter-prop="children"
          >
            <a-select-option v-for="item in processList" :key="item.value">{{
              $t(item.label)
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :label="$t('breach.steps.step2.business.form.call.remark')"
        >
          <a-textarea
            rows="4"
            :placeholder="$t('breach.steps.step2.turn.remark.placeholder')"
            v-decorator="['BreachCommentsInfo']"
            :disabled="!ifCanEdit"
          ></a-textarea>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="closeModal">{{
          $t("app.setting.content-width.fluid2222333")
        }}</a-button>
        <a-button type="primary" @click="turnTo" :loading="btnLoading">{{
          $t("breach.steps.step2.buttons.turn")
        }}</a-button>
      </template>
    </a-modal>
    <div class="big-box" v-if="ifLoading">
      <a-spin />
    </div>
  </div>
</template>

<script>
import {
  changeSupplementStatus,
  createLog,
  dataBreachTransfer,
  deleteCooperater,
  deleteSupplement,
  dispatchUser,
  getCooperateList,
  getProcessorList,
  getSupplementList,
  refuseSupplement,
} from "@/api/dataBreach/form";
import step1 from "./step1.vue";
import step2Form from "./step2Form.vue";
import {
  createSupplement,
  sendEmail,
  addCooperater,
  createFile,
} from "@/api/dataBreach/json";
import { getUserList } from "@/api/common/form";
import deepClone from "lodash.clonedeep";
export default {
  name: "step2",
  components: { step1, step2Form },
  props: ["breachMode", "lang", "breachDetail", "ifCanEdit", "role", "current", "ifReviewing"],
  data() {
    return {
      businessList: [],
      handlerList: [],
      form: this.$form.createForm(this),
      visible: false,
      childBreachDetail: {},
      ifLoading: false,
      processList: [],
      businessInit: {
        PersonalInformation: null,
        SupplementBmw: null,
        SupplementController: undefined,
        SupplementControllerOther: "",
        SupplementControllerStr: "",
        SupplementDescribe: "",
        SupplementInformationType: [],
        SupplementInside: null,
        SupplementInternalSystems: [],
        SupplementInternalSystemsOther: "",
        SupplementNumber: "",
        SupplementOtherInformation: "",
        SupplementProcessingActivities: 2,
        SupplementProcessingActivitiesSupplement: "",
        SupplementRealData: 1,
        SupplementRemark: "",
        SupplementStatus: 1,
        SupplementThird: null,
        SupplementUser: undefined,
        SupplementUserId: 0,
        frontTemp: {
          ifPatched: false,
          ifShrink: true,
        },
        collaborators: [],
      },
      btnLoading: false
    };
  },
  mounted() {
    this.getProcessors();
  },
  watch: {
    breachDetail: {
      async handler(newVal) {
        this.childBreachDetail = newVal;
        if (newVal.EventStatus === 4) {
          this.getSupplements();
        }
      },
      immediate: true,
    },
    current: {
      handler(newVal) {
        if (newVal === 1) {
          this.getSupplements();
        }
      },
    },
    ifReviewing: {
      handler(newVal) {
        if(!newVal) {
          this.getSupplements();
        }
      },
    }
  },
  methods: {
    async patchUser(row) {
      this.btnLoading = true
      // 保存基本信息
      let { code } = await this.saveDraft("refresh", {}, row.Id, true);
      // 存log信息
      createLog({
        BreachId: this.breachDetail?.Id,
        LogUserId: this.$store.state.user.info.YtId,
        LogUserName: this.$store.state.user.info.YtAdminUserName,
        LogOperation: `${this.$store.state.user.info.YtAdminUserName}分配业务填报`,
      });
      if (code === 1) {
        this.getSupplements();
        this.$message.success(
          this.$t("breach.steps.step2.business.patch.success")
        );
        row.frontTemp.ifPatched = true;
        row.status = 2;
      } else {
        this.$message.error(this.$t("breach.steps.step2.business.patch.fail"));
      }
      this.btnLoading = false
    },
    changeItem(item, key, value) {
      item[key] = value;
    },
    async delBussiness(Id) {
      if (Id > 10000000) {
        this.businessList = this.businessList.filter((item) => {
          return item.Id !== Id;
        });
        return;
      }
      deleteSupplement({ Id });
      this.getSupplements();
    },
    closeModal() {
      this.visible = false;
      this.form.resetFields();
    },
    async turnTo() {
      this.form.validateFields(async (error, value) => {
        if (!error) {
          this.btnLoading = true
          // 转办
          let { code } = await dataBreachTransfer({
            Id: this.breachDetail.Id,
            ...value,
            BreachCommentsProcessor: this.processList.filter(
              (item) => item.value === value.BreachCommentsProcessorId
            )[0]?.label,
          });
          if (code === 1) {
            this.$message.success(
              this.$t("user.verification-code.required111566110577269")
            );
            this.saveDraft();
          }
          this.btnLoading = false
        }
      });
    },
    async delCollaborator(row, collaborator, ind) {
      // 已填报不可删除
      if (row.SupplementStatus !== 3) {
        if (collaborator.Id > 10000000) {
          row.collaborators = row.collaborators.filter(
            (_, index) => index !== ind
          );
        } else {
          let res = await deleteCooperater({ Id: collaborator.Id });
          if (res.code === 1) {
            this.$message.success(
              this.$t("user.verification-code.required111566110577133")
            );
            row.collaborators = row.collaborators.filter(
              (_, index) => index !== ind
            );
          }
        }
      }
    },
    async getSupplements() {
      this.businessList = [];
      let { data } = await getSupplementList({
        page: 1,
        pageSize: 100000,
        BreachId: this.breachDetail.Id,
      });
      if (data.Lists.length) {
        this.businessList = data.Lists.map((item) => {
          this.getCooperates(item.Id);
          return {
            ...item,
            frontTemp: {
              ifPatched: item.SupplementStatus !== 1 ? true : false,
              ifShrink: true,
            },
            // 初始化
            collaborators: [],
            SupplementUser: !item.SupplementUser
              ? undefined
              : item.SupplementUser,
            SupplementRealData:
              item.SupplementRealData === 0 ? 1 : item.SupplementRealData,
            SupplementProcessingActivities:
              item.SupplementProcessingActivities === 0
                ? 2
                : item.SupplementProcessingActivities,
            SupplementInformationType: !item.SupplementInformationType
              ? []
              : item.SupplementInformationType.split(","),
            SupplementController:
              item.SupplementController === ""
                ? undefined
                : item.SupplementController.split(",").map((item) =>
                    Number(item)
                  ),
            SupplementInternalSystems:
              item.SupplementInternalSystems.split(","),
          };
        });
      } else {
        this.addSupplement();
      }
    },
    async addSupplement() {
      let cloneInit = deepClone(this.businessInit);
      this.businessList.push({
        Id: +new Date(),
        BreachId: this.breachDetail.Id,
        ...cloneInit,
      });
    },
    async getUsers(value) {
      const { data } = await getUserList({
        UserEmail: value,
        UserName: value,
      });
      this.handlerList = data;
    },
    async getCooperates(Id) {
      let { data } = await getCooperateList({ SupplementId: Id });
      let item = this.businessList.filter((item) => item.Id === Id)[0];
      if (item) item.collaborators = data;
    },
    async saveDraft(type, backVal, changeStatusId, ifUpdate = false) {
      this.ifLoading = true;
      // 保存基本信息
      await this.$refs.step1.addBreach("draft", false);
      // 处理所有补充信息
      let tempBusList = [...this.businessList];
      let newBusList = [];
      let resBusList = [];
      tempBusList.forEach((item, ind) => {
        this.saveItem(item, false, ind);
        if (changeStatusId && changeStatusId === item.Id) {
          // 分派通知-新建时修改状态
          item.SupplementStatus = 2;
        }
        if (item.Id > 100000000) {
          // 新增的补充判断是否保存
          for (const key in item) {
            if (Object.hasOwnProperty.call(item, key)) {
              const element = item[key];
              if (element) {
                if (key === "BreachId") continue;
                let notKeyVal = {
                  SupplementProcessingActivities: 2,
                  SupplementRealData: 1,
                  SupplementStatus: 1,
                };
                if (element !== notKeyVal[key]) {
                  newBusList.push(item);
                  item.Id = undefined;
                  resBusList.push(item);
                  break;
                }
              }
            }
          }
        } else {
          resBusList.push(item);
        }
      });
      let res = await createSupplement({
        BreachSupplementArr: resBusList,
      });
      if (changeStatusId) {
        // 发邮件并更新邮件列表
        let index = 0;
        newBusList.forEach((item, ind) => {
          if (item.Id === changeStatusId) {
            index = ind;
          }
        });
        await dispatchUser({
          Id: res.data.split(",")[index],
          BreachId: this.breachDetail.Id,
        });
        if(ifUpdate) {
           // 分派并更新状态
          this.$emit("updateEmail");
        }
      }
      this.ifLoading = false;
      if (type !== "refresh") {
        this.$message.success(
          this.$t("user.verification-code.required111566110577308")
        );
        this.$emit("changeIfFlag", true);
        this.$router.push("/breach/list");
      } else {
        if (backVal && backVal.Id) {
          // 退回
          let { code: backCode } = await refuseSupplement(backVal);
          if (backCode === 1) {
            this.$message.success(this.$t("breach.steps.step2.modal.back.tip"));
            this.getSupplements();
          }
        }
        return { code: res.code };
      }
    },
    async addCollaborator(Id, arr) {
      arr = arr.map((item) => {
        return {
          Id: item.Id > 1000000 ? undefined : "",
          ...item,
          SupplementId: Id,
        };
      });
      if (arr.length) await addCooperater({ CooperationArr: arr });
      this.getCooperates(Id);
    },
    async changeStep(step) {
      if (step !== 2 || this.ifCanEdit) {
        await this.saveDraft("refresh");
      }
      this.$emit("changeCurrent", step);
    },
    async getProcessors() {
      let { data } = await getProcessorList();
      this.processList = data;
    },
    async saveItem(item, childMode, index) {
      // 保存协作者信息
      let saveCollaborator = item.collaborators.filter(
        (item) => item.SharingUser
      );
      this.addCollaborator(item.Id, saveCollaborator);
      if (childMode) {
        // 获取index
        this.businessList.forEach((business, ind) => {
          if (business.Id === item.Id) {
            index = ind;
          }
        });
      }
      let allLists = this.$refs[`step2Form${index}`][0].getAllLists();
      let formInfo = this.$refs[`step2Form${index}`][0].form.getFieldsValue();
      let cancat = { ...allLists, ...formInfo };
      for (const key in cancat) {
        // 附件BreachFileArr单独处理
        if (Object.hasOwnProperty.call(cancat, key)) {
          if (key !== "BreachFileArr") {
            item[key] = cancat[key];
          } else {
            cancat[key].length
              ? createFile({ BreachFileArr: cancat[key] })
              : "";
          }
        }
      }
      item.SupplementInformationType = item.SupplementInformationType?.join(",");
      item.SupplementController = item.SupplementController
        ? typeof item?.SupplementController === "string"
        ? item.SupplementController
        : item?.SupplementController?.join(",")
        : "";
      item.PersonalInformation = undefined;
      item.SupplementBmw = undefined;
      item.SupplementInside = undefined;
      item.SupplementThird = undefined;
      item.SupplementInternalSystems = item.SupplementInternalSystems
        ? item.SupplementInternalSystems.join(",")
        : "";
      if (childMode) {
        let res = await createSupplement({
          BreachSupplementArr: [item],
        });
        // 提交-改补充信息状态
        if (childMode === "submit") {
          res = await changeSupplementStatus({
            Id: item.Id,
            SupplementStatus: 3,
          });
        }
        if (res.code === 1) {
          this.$message.success(
            this.$t("user.verification-code.required111566110577308")
          );
          this.$emit("changeIfFlag", true);
          this.$router.push("/breach/list");
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.step2 {
  h3 {
    background-color: #d2dcec;
    padding: 2px 6px;
    font-size: 18px;
  }
  .business {
    border: 1px solid #bbb;
    position: relative;
    .status-steps {
      position: absolute;
      top: 4px;
      right: 30px;
      display: flex;
      align-items: center;
      color: #a1a1a2;
      i {
        margin: 0 10px;
      }
      .orange {
        color: #eb903a;
      }
      .light-green {
        color: #8ace55;
      }
      .green {
        color: #569b30;
      }
      .blue {
        color: #3b84f4;
      }
      .light-blue {
        color: #5877a1;
      }
    }
    .delete-btn {
      position: absolute;
      top: -2px;
      right: 0px;
    }
    .patch,
    .collaborators {
      display: flex;
      padding: 0 20px;
      margin-bottom: 10px;
      align-items: center;
      label {
        span {
          display: inline-block;
          min-width: 60px;
        }
      }
      .ant-select {
        width: 200px;
        margin: 0 20px;
      }
      .ant-btn {
        display: flex;
        align-items: center;
        padding: 0;
      }
      & > .anticon.anticon-minus-circle {
        font-size: 20px;
        color: red;
        cursor: pointer;
        &.disabled {
          color: #a1a1a2;
        }
      }
    }
    footer {
      height: 30px;
      background-color: #cbdcf0;
      display: flex;
      flex-direction: row-reverse;
      i.anticon {
        transform: rotate(-90deg);
      }
    }
  }
  .big-box {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.7);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9999999;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>